import { _decorator, Component, Node, RigidBody2D, v3,Vec2, Vec3 } from 'cc';
import { DIR } from '../Common';
import { Vector3 } from '../Math/Vector3';
const { ccclass, property } = _decorator;

@ccclass('TankMove')
export class TankMove extends Component {
    
    @property  dir:Vec3=DIR.left.clone();

    @property speed:number=5.6;

    @property isMove:boolean=false;

    rb2d:RigidBody2D|null=null;

    onLoad() {
        this.rb2d=this.node.getComponent(RigidBody2D);
        this.updateDir();
    }

    getDir(){
        return this.dir.clone();
    }

    changeMoveState(state:boolean){
        if(this.isMove!==state){

            this.isMove=state;
            
            if(this.isMove===true){
                this.node.emit("CHANGE_MOVE_STATE",true);
                //console.log("tank dir"+this.dir);
            }else if(this.isMove===false){
                this.node.emit("CHANGE_MOVE_STATE",false);
            }
        }
    }
    changeDir(dir:Vec3):void{
        this.dir =dir.clone();
        this.updateDir();
    }
        
    updateDir(){

      //  console.log(JSON.stringify(DIR));
        if(Vector3.ValEqual(this.dir,DIR.left)){

       //     console.log("l e"+this.dir+":"+DIR.left);
            this.node.setRotationFromEuler(new Vec3(0,0,0));
        }else if(Vector3.ValEqual(this.dir,DIR.top)){
            this.node.setRotationFromEuler(new Vec3(0,0,-90));
        }else if(Vector3.ValEqual(this.dir,DIR.right)){
            this.node.setRotationFromEuler(new Vec3(0,0,-180));
        }else if(Vector3.ValEqual(this.dir,DIR.bottom)){
            this.node.setRotationFromEuler(new Vec3(0,0,-270));
        }
    }

    changePos(deltaTime:number){
        if(this.isMove===false) return;

        let {x,y}=this.node.position;
        if( Vector3.ValEqual(this.dir,DIR.left) ){
            x-=deltaTime*this.speed;
        }else if(Vector3.ValEqual(this.dir,DIR.top) ){
            y+=deltaTime*this.speed;
            this.node.setRotationFromEuler(new Vec3(0,0,-90));
        }else if(Vector3.ValEqual(this.dir,DIR.right) ){
            x+=deltaTime*this.speed;
            this.node.setRotationFromEuler(new Vec3(0,0,-180));
        }else if(Vector3.ValEqual(this.dir,DIR.bottom) ){
            y-=deltaTime*this.speed;
            this.node.setRotationFromEuler(new Vec3(0,0,-270));
        }
    
        /*
        if(this.node.name==="player"){

            console.log("move"+this.isMove);
            }
            */

        this.node.setPosition(x,y);
       // this.rb2d.linearVelocity=new Vec2(x,y);
    }

    update(deltaTime: number) {
 
        this.changePos(deltaTime);   
    }
}


